package dnl.toolbox.files;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

import de.schlichtherle.io.ArchiveDetector;
import de.schlichtherle.io.DefaultArchiveDetector;

/**
 * An <code>Archiver</code> that is based on the truezip library.
 * 
 * @author Daniel Orr
 *
 */
public class TruezipArchiver implements Archiver {

	static {
		de.schlichtherle.io.File
				.setDefaultArchiveDetector(new DefaultArchiveDetector(
						ArchiveDetector.ALL, new String[0]));
	}
	
	@Override
	public void createZip(File sourceDir, File target, boolean deleteOrigin) throws IOException {
		de.schlichtherle.io.File archive = new de.schlichtherle.io.File(target);
		de.schlichtherle.io.File src = new de.schlichtherle.io.File(sourceDir);

		src.archiveCopyAllTo(archive);
		de.schlichtherle.io.File.umount(archive);
		if (deleteOrigin) {
			FileUtils.forceDelete(sourceDir);
			if (sourceDir.exists()) {
				throw new IllegalStateException("could not delete source dir - "
						+ sourceDir.getAbsolutePath());
			}
		}
	}

	@Override
	public void unzip(File zipFile, File target, boolean deleteOrigin) {
		 de.schlichtherle.io.File srcZip = new de.schlichtherle.io.File(zipFile.getAbsolutePath());
		 srcZip.archiveCopyAllTo(target);
		 if (deleteOrigin) {
				try {
					FileUtils.forceDelete(zipFile);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (zipFile.exists()) {
					throw new IllegalStateException("could not delete source dir - "
							+ zipFile.getAbsolutePath());
				}
			}
	}

}
